package com.googlecode.cswish.struts.conversion;

import javax.annotation.Resource;

import com.googlecode.cswish.model.PageElement;
import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.model.PropertyInfo;
import com.googlecode.cswish.struts.spring.BeanIntrospector;

public class PageInfoPageConverter implements ElementConverter {
	@Resource
	private BeanIntrospector beanIntrospector;
	
	@Resource
	private ModelPageConverter modelPageConverter;
	
	public PageElement convert(ConversionContext context) {
		String itemType = getFullName(context.getClassName());
		ConversionContext newContext = context.clone();
		PropertyInfo propertyInfo = newContext.getPropertyInfo();
		// Only convert pageInfo.data
		propertyInfo.setType(itemType);
		propertyInfo.setGenericType(itemType);
		PageElements pageElement = (PageElements) modelPageConverter.convert(newContext);
		pageElement.setType("datagrid");
		pageElement.addExtraParams("itemType", itemType);
		return pageElement;
	}
	
	private String getFullName(String shortName) {
		if (shortName.startsWith("java.lang.")) {
			int index = shortName.lastIndexOf('.') + 1;
			if (Character.isLowerCase(shortName.charAt(index))) {
				return shortName.substring(0, index)
					+ Character.toUpperCase(shortName.charAt(index))
					+ shortName.substring(index + 1);
			} else {
				return shortName;
			}
		} else {
			return beanIntrospector.getModelName(beanIntrospector.getSimpleName(shortName));
		}
	}
}
